package com.github.jcooky.structure;

import java.util.Arrays;

public class Array implements ArrayList {
	private Object[] A;
	private int n = 0;
	
	public Array() {
		this(32);
	}
	
	public Array(int capacity) {
		A = new Object[capacity];
	}

	public Object get(int i) {
		return A[i];
	}

	public Object set(int i, Object e) {
		Object o = A[i];
		if (i >= n) {
			i = n++;
		}
		A[i] = e;
		return o;
	}

	public void add(int i, Object e) {
		if (n == A.length) {
			A = Arrays.copyOf(A, A.length * 2);
		}
		if (i < n) {
			Object o = A[i];
			for (int j = i+1; j < n; ++j) {
				Object o2 = A[j];
				A[j] = o;
				o = o2;
			}
		} else if (i >= n) {
			i = n;
		}
		A[i] = e;
		++n;
	}

	public Object remove(int i) {
		Object o = null;
		if (i < n) {
			o = A[n-1];
			for (int j = n - 2; j >= i; --j) {
				Object o2 = A[j];
				A[j] = o;
				o = o2;
			}
		} else if (i >= n) {
			return null;
		}
		--n;
		return o;
	}

	public int size() {
		return n;
	}

	public boolean isEmpty() {
		return n == 0;
	}
	
	public Iterator iterator() {
		return new Iterator() {
			private int index = 0;
			
			public boolean hasNext() {
				return index < size();
			}

			public Object next() {
				return get(index++);
			}
			
		};
	}
}
